import math


def get_real_number():
    """获取实数输入"""
    while True:
        try:
            num = float(input("请输入数字："))
            return num
        except ValueError:
            print("输入无效，请输入实数！")


def get_complex_number():
    """获取复数输入"""
    while True:
        try:
            text = input("请输入复数（格式如3+4j）：").replace(' ', '')
            num = complex(text)
            return num
        except ValueError:
            print("格式错误，请按示例格式输入！")


def real_operations():
    """实数运算处理"""
    print("\n可用运算符：+  -  *  /  ^2  sqrt  sin  cos  tan  lg")
    op = input("请选择运算符：").strip().lower()

    # 二元运算
    if op in ('+', '-', '*', '/'):
        print("输入第一个数：")
        a = get_real_number()
        print("输入第二个数：")
        b = get_real_number()

        try:
            if op == '+':
                res = a + b
            elif op == '-':
                res = a - b
            elif op == '*':
                res = a * b
            elif op == '/':
                res = a / b
            print(f"计算结果：{res:.4f}")
        except ZeroDivisionError:
            print("错误：除数不能为零！")

    # 一元运算
    elif op in ('^2', 'sqrt', 'sin', 'cos', 'tan', 'lg'):
        print("输入操作数：")
        a = get_real_number()

        try:
            if op == '^2':
                res = a ** 2
            elif op == 'sqrt':
                if a < 0: raise ValueError
                res = math.sqrt(a)
            elif op == 'sin':
                res = math.sin(math.radians(a))
            elif op == 'cos':
                res = math.cos(math.radians(a))
            elif op == 'tan':
                res = math.tan(math.radians(a))
            elif op == 'lg':
                if a <= 0: raise ValueError
                res = math.log10(a)
            print(f"计算结果：{res:.4f}")
        except ValueError:
            print("错误：输入参数超出有效范围！")

    else:
        print("无效的运算符！")


def complex_operations():
    """复数四则运算"""
    print("\n输入第一个复数：")
    a = get_complex_number()
    print("输入第二个复数：")
    b = get_complex_number()
    op = input("选择运算符（+  -  *  /）：").strip()

    try:
        if op == '+':
            res = a + b
        elif op == '-':
            res = a - b
        elif op == '*':
            res = a * b
        elif op == '/':
            res = a / b
        else:
            print("无效运算符！")
            return
        print(f"计算结果：{res:.4f}")
    except ZeroDivisionError:
        print("错误：除数不能为零！")


def main():
    print("========= wzm科学计算器 =========")
    while True:
        print("\n1. 实数运算模式")
        print("2. 复数运算模式")
        print("q. 退出程序")
        choice = input("请选择模式：").lower()

        if choice == '1':
            real_operations()
        elif choice == '2':
            complex_operations()
        elif choice == 'q':
            print("感谢使用联想科学计算器！")
            break
        else:
            print("无效的输入，请重新选择！")


if __name__ == "__main__":
    main()